<template>
  <div id="order-page">
    <ContentField>
      <template v-slot:content-field-card-name>{{ title }}页面</template>
      <template v-slot:content-field-card-button>
        <div>
          <el-button type="warning" @click="clearCart">清空选项</el-button>
          <el-button type="success" @click="foodCartBtnClicked"
            >购物车</el-button
          >
        </div>
      </template>
      <template v-slot:content-field-card-body>
        <div style="position: relative">
          <el-table
            ref="multipleTableRef"
            :data="food_list"
            style="
              position: absolute;
              width: 100%;
              overflow-y: scroll;
              height: 64vh;
            "
            :row-key="getRowKeys"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              :reserve-selection="true"
              min-width="3%"
            />
            <el-table-column prop="name" label="名称" min-width="12%" />
            <el-table-column prop="foodStyleName" label="种类" min-width="6%" />
            <el-table-column prop="price" label="价格" min-width="6%" />
          </el-table>
        </div>
      </template>
      <template v-slot:content-field-card-footer></template>
    </ContentField>
    <!-- 菜品清单 -->
    <el-dialog v-model="foodCartVisible" title="菜品清单" style="width: 80%">
      <el-table :data="select_food_list">
        <el-table-column property="name" label="名称" min-width="12%" />
        <el-table-column property="foodStyleName" label="种类" min-width="6%" />
        <el-table-column property="price" label="价格" min-width="6%" />
        <el-table-column label="数量" min-width="12%">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.num"
              size="small"
              style="width: 70px"
              :min="0"
              :max="100"
              @change="handleFoodNumChange(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-row>
            <el-col :span="6">
              <el-statistic title="总价" :value="total_price" />
            </el-col>
            <el-col :span="12">
              <el-button @click="foodCartVisible = false">Cancel</el-button>
              <el-button type="primary" @click="addOrderBtnClicked">
                Confirm
              </el-button>
            </el-col>
          </el-row>
        </span>
      </template>
    </el-dialog>
    <!-- 确认提交 -->
    <el-dialog v-model="confirmSubVisible" title="确认订单">
      <el-form :model="confirmForm">
        <el-form-item label="人数" label-width="100">
          <el-input-number
            v-model="confirmForm.client_num"
            size="small"
            style="width: 200px"
            :min="1"
            :max="100"
          />
        </el-form-item>
        <el-form-item label="是否预定" label-width="100">
          <el-select
            v-model="confirmForm.is_predetermine"
            default-first-option=""
            placeholder="是否预定"
            style="width: 200px"
          >
            <el-option label="否" value="0" />
            <el-option label="是" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="桌号" label-width="100">
          <el-select
            v-model="confirmForm.table_id"
            class="m-2"
            style="width: 200px"
            placeholder="Select"
          >
            <el-option
              v-for="item in table_list"
              :key="item.id"
              :label="item.id"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="预定时间"
          label-width="100"
          v-show="confirmForm.is_predetermine == '1'"
        >
          <el-time-select
            style="width: 200px"
            v-model="confirmForm.time"
            :start="start_time"
            step="00:15"
            end="23:30"
            placeholder="Select time"
          />
        </el-form-item>
        <el-form-item label="总价格" label-width="100">
          <el-input
            v-model="confirmForm.total_price"
            disabled
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmSubVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmSubBtnClicked">
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import ContentField from "@/components/ContentField.vue";
import { computed, ref, reactive } from "vue";
import { useStore } from "vuex";
import dateUtil from "@/util/date";
import { ElNotification } from "element-plus";

export default {
  components: {
    ContentField,
  },
  setup() {
    let store = useStore();

    store.dispatch("get_all_table", {
      token: store.state.user.jwt_token,
    });

    let table_list = computed(() => {
      return store.state.table.table_list;
    });

    // 判断是点餐还是预定
    let title = computed(() => {
      if (store.state.order.is_predetermine) {
        return "预定";
      } else {
        return "点单";
      }
    });
    // 进入页面先获取所有食物
    store.dispatch("get_all_food");
    // 取出store中的food_list
    let food_list = computed(() => {
      return store.state.food.food_list;
    });

    const multipleTableRef = ref();
    const select_order_number = ref(""); //表格select选中的条数
    const select_orderId = ref([]); //表格select复选框选中的id
    const multipleSelection = ref([]);

    //选中的list
    const getRowKeys = (row) => {
      //记录每行的key值
      return row.id;
    };
    //当表格选择项发生变化时会触发该事件
    const handleSelectionChange = (val) => {
      // 解决来回切换页面，也无法清除上次选中情况
      multipleSelection.value = val;
      select_order_number.value = multipleSelection.value.length;
      select_orderId.value = [];
      if (val) {
        undefined;
        val.forEach((row) => {
          undefined;
          if (row) {
            undefined;
            select_orderId.value.push(row.id);
          }
        });
      }
      // console.log(select_orderId.value);
    };
    const clearCart = () => {
      multipleTableRef.value.clearSelection();
    };

    // 购物车相关
    let foodCartVisible = ref(false);
    let confirmSubVisible = ref(false);

    let foodCartBtnClicked = () => {
      foodCartVisible.value = true;
    };

    let select_food_list = computed(() => {
      let res = [];
      for (let i = 0; i < food_list.value.length; i++) {
        let food = food_list.value[i];
        for (let j = 0; j < select_orderId.value.length; j++) {
          if (select_orderId.value[j] == food.id) {
            food.num = 1;
            res.push(food);
          }
        }
      }
      return res;
    });

    let total_price = computed(() => {
      let res = 0;
      for (let i = 0; i < select_food_list.value.length; i++) {
        let food = select_food_list.value[i];
        res += food.num * food.price;
      }
      return res;
    });

    let handleFoodNumChange = (row) => {
      console.log(row.num);
    };

    let confirmForm = reactive({
      is_predetermine: store.state.order.is_predetermine ? "1" : "0",
      client_num: 1,
    });

    let addOrderBtnClicked = () => {
      confirmSubVisible.value = true;
      confirmForm.total_price = total_price.value;
    };

    let confirmSubBtnClicked = () => {
      confirmSubVisible.value = true;
      confirmForm.token = store.state.user.jwt_token;
      confirmForm.client_id = store.state.client.id;
      confirmForm.food_list = select_food_list.value;
      confirmForm.predetermine_time =
        dateUtil.formatDate(new Date()).substring(0, 11) +
        confirmForm.time +
        ":00";

      store.dispatch("add_order_and_items", {
        confirmForm,
        success(data) {
          if (data.code == 200) {
            confirmSubVisible.value = false;
            foodCartVisible.value = false;
            ElNotification.success({
              title: "Success",
              message: "订单提交成功，请耐心等待。",
              offset: 100,
            });
          }
        },
        error(data) {
          ElNotification.error({
            title: "Error",
            message: "订单提交失败：" + data.message,
            offset: 100,
          });
        },
      });
    };

    let start_time = computed(() => {
      const date = new Date();
      return (date.getHours() + 1).toString() + ":00";
    });

    return {
      title,
      food_list,
      table_list,
      start_time,
      total_price,
      confirmForm,
      multipleTableRef,
      foodCartVisible,
      confirmSubVisible,
      select_food_list,
      getRowKeys,
      clearCart,
      handleFoodNumChange,
      handleSelectionChange,
      addOrderBtnClicked,
      foodCartBtnClicked,
      confirmSubBtnClicked,
    };
  },
};
</script>

<style scoped></style>
